package cn.com.anypay.manager.miaoma.suantaiqrcode.handler.impl;

import cn.com.anypay.manager.miaoma.suantaiqrcode.SuantaiQrcodeEntity;
import cn.com.anypay.manager.miaoma.suantaiqrcode.handler.AbstractQrCodeHandler;
import cn.com.anypay.manager.common.response.ApiResponse;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

/**
 * 轮询码类型二维码处理器 (type = 8)
 *
 * 轮询码包含多个URL，每次扫码会根据时间戳随机选择一个URL进行跳转
 */
@Slf4j
@Component
public class PollingQrCodeHandler extends AbstractQrCodeHandler {

    private static final Integer SUPPORTED_TYPE = 8;
    private static final String HANDLER_NAME = "PollingQrCodeHandler";

    @Override
    public ApiResponse<Object> handle(SuantaiQrcodeEntity qrcode, String id) {
        logHandleStart(id);

        if (!isValidContent(qrcode.getContent())) {
            logHandleComplete(id, "Content is empty");
            return createErrorResponse(HttpStatus.BAD_REQUEST, "Content is empty");
        }

        JsonNode content = parseJsonContent(qrcode.getContent());
        if (content == null) {
            logHandleComplete(id, "Failed to parse JSON content");
            return createErrorResponse(HttpStatus.BAD_REQUEST, "Invalid JSON content");
        }

        String targetUrl = selectPollingUrl(content, id);
        if (targetUrl == null) {
            logHandleComplete(id, "No valid URL found in polling items");
            return createErrorResponse(HttpStatus.BAD_REQUEST, "No valid URL found in polling items");
        }

        logHandleComplete(id, "Polling redirect to: " + targetUrl);
        return createRedirectResponse(targetUrl);
    }

    /**
     * 从轮询项目中选择一个URL
     *
     * @param content JSON内容
     * @param id 二维码ID，用于日志记录
     * @return 选中的URL
     */
    private String selectPollingUrl(JsonNode content, String id) {
        JsonNode items = content.get("items");
        if (items == null || !items.isArray() || items.size() == 0) {
            log.warn("[{}] No items array found or array is empty in polling QR code, id: {}",
                     getHandlerName(), id);
            return null;
        }

        // 使用时间戳进行轮询选择
        int selectedIndex = (int) (System.currentTimeMillis() % items.size());
        JsonNode selectedItem = items.get(selectedIndex);

        if (selectedItem == null) {
            log.warn("[{}] Selected item is null, index: {}, id: {}",
                     getHandlerName(), selectedIndex, id);
            return null;
        }

        JsonNode urlNode = selectedItem.get("url");
        if (urlNode == null) {
            log.warn("[{}] URL not found in selected item, index: {}, id: {}",
                     getHandlerName(), selectedIndex, id);
            return null;
        }

        String url = urlNode.asText();
        if (url == null || url.trim().isEmpty()) {
            log.warn("[{}] URL is empty in selected item, index: {}, id: {}",
                     getHandlerName(), selectedIndex, id);
            return null;
        }

        log.info("[{}] Selected polling URL, index: {}, url: {}, id: {}",
                 getHandlerName(), selectedIndex, url, id);

        return url;
    }

    @Override
    public Integer getSupportedType() {
        return SUPPORTED_TYPE;
    }

    @Override
    public String getHandlerName() {
        return HANDLER_NAME;
    }

    @Override
    public ApiResponse<Object> handleForGateway(SuantaiQrcodeEntity qrcode, String id) {
        logHandleStart(id);

        if (!isValidContent(qrcode.getContent())) {
            logHandleComplete(id, "Content is empty");
            return createErrorResponse(HttpStatus.BAD_REQUEST, "Content is empty");
        }

        JsonNode content = parseJsonContent(qrcode.getContent());
        if (content == null) {
            logHandleComplete(id, "Failed to parse JSON content");
            return createErrorResponse(HttpStatus.BAD_REQUEST, "Invalid JSON content");
        }

        String targetUrl = selectPollingUrl(content, id);
        if (targetUrl == null) {
            logHandleComplete(id, "No valid URL found in polling items");
            return createErrorResponse(HttpStatus.BAD_REQUEST, "No valid URL found in polling items");
        }

        // 为网关模式返回结构化数据
        logHandleComplete(id, "Preparing polling redirect data for gateway: " + targetUrl);
        return createGatewayRedirectResponse(
            qrcode.getQrCodeId(),
            qrcode.getQrCodeName(),
            qrcode.getQrCodeType(),
            targetUrl
        );
    }
}